package org.dxy.domain.handler.productionLine;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.adapter.port.CommandHandler;
import org.dxy.domain.adapter.repository.IProductionLineRepository;
import org.dxy.domain.adapter.repository.IWorkstationRepository;
import org.dxy.domain.command.productionLine.AddWorkstationToLineCommand;
import org.dxy.domain.model.aggregate.ProductionLine;
import org.dxy.domain.model.aggregate.Workstation;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 添加工作站到产线命令处理器
 * @author: dxy
 * @createTime: 2025/6/26 10:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AddWorkstationToLineCommandHandler implements CommandHandler<AddWorkstationToLineCommand, Void> {
    private final IProductionLineRepository productionLineRepository;
    private final IWorkstationRepository workstationRepository;
    private final EventBus eventBus;

    @Override
    public CommandResult<Void> handle(AddWorkstationToLineCommand command) {
        // 1. 获取产线聚合
        ProductionLine line = productionLineRepository.findById(command.getLineId());
        if (line == null) {
            log.error("未找到产线，command={}", command);
            return CommandResult.fail("产线不存在");
        }

        // 2. 获取工位
        Workstation workstation = workstationRepository.findById(command.getWorkstationId());
        if (workstation == null) {
            log.error("未找到工位，command={}", command);
            return CommandResult.fail("工位不存在");
        }
        // 4. 调用聚合根添加工位方法（内部会添加事件到事件列表）
        line.addWorkstation(command, workstation);

        // 5. 持久化变更
        productionLineRepository.save(line);

        // 6. 发布聚合产生的所有事件
        line.getDomainEvents().forEach(eventBus::post);

        // 7. 清理事件，防止重复发布
        line.clearDomainEvents();

        log.info("添加工作站到产线成功, command={}", command);
        return CommandResult.success("添加工作站到产线成功");
    }
}